package com.codenjoy.calculator.base;


/**
 * Created by kate on 31.01.2015.
 */
public class ArabianBase implements Base {
    static final String ARABIAN_SYSTEM_SYMBOLS = "0123456789ABCDEFG";

    private final int currentBase;

    protected ArabianBase(int currentBase) {
        this.currentBase = currentBase;
    }

    @Override
    public long formatFromBaseToDecimal(String numberInBaseFormat) {
        long numberInDecimal = 0;
        for (int i = 0; i < numberInBaseFormat.length(); i++) {
            char tempSymbol = numberInBaseFormat.charAt(i);
            numberInDecimal = currentBase * numberInDecimal + ARABIAN_SYSTEM_SYMBOLS.indexOf(tempSymbol);
        }
        return numberInDecimal;
    }

    @Override
    public String formatFromDecimalToBase(long num) {
        String res = "";
        long l = num;
        do {
            int h = (int) (l % currentBase);
            l = l / currentBase;
            res = ARABIAN_SYSTEM_SYMBOLS.charAt(h) + res;
        } while (l >= 1);
        return res;
    }

    @Override
    public void validateSymbol(char symbol) {
        int in = ARABIAN_SYSTEM_SYMBOLS.indexOf(symbol);
        if (in < 0 || in >= currentBase) {
            throw new IllegalArgumentException("Invalid number");
        }
    }

}
